package com.jn.okhttps_demo01.views;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jn.okhttps_demo01.R;
import com.jn.okhttps_demo01.model.HotSearchItem;

import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = findViewById(R.id.listView);
        fetchHotSearchBoard();
    }

    private void fetchHotSearchBoard() {
        //GET请求示例
//        OkHttpClient client = new OkHttpClient();
//        String url = "https://api.oioweb.cn/api/common/fetchHotSearchBoard?type=baidu";
//
//        Request request = new Request.Builder()
//                .url(url)
//                .build();
//
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(@NonNull Call call, @NonNull IOException e) {
//                e.printStackTrace();
//                runOnUiThread(() -> Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show());
//            }
//
//            @Override
//            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    final String jsonData = response.body().string();
//                    runOnUiThread(() -> parseAndDisplayData(jsonData));
//                }
//            }
//        });
//      //POST请求示例：
        OkHttpClient client = new OkHttpClient();

// 创建RequestBody，发送表单数据
        RequestBody requestBody = new FormBody.Builder()
                .add("type", "baidu") // 添加表单字段
                .build();

// 构建POST请求
        Request request = new Request.Builder()
                .url("https://api.oioweb.cn/api/common/fetchHotSearchBoard")
                .post(requestBody)
                .build();

// 发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(() -> Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String responseData = response.body().string();
                    runOnUiThread(() -> {
                        try {
                            // 处理响应数据
                            parseAndDisplayData(responseData);
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(MainActivity.this, "解析数据失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    runOnUiThread(() -> Toast.makeText(MainActivity.this, "请求不成功", Toast.LENGTH_SHORT).show());
                }
            }
        });
//        OkHttpClient client = new OkHttpClient();
//
//        RequestBody requestBody = new MultipartBody.Builder()
//                .setType(MultipartBody.FORM)
//                .addFormDataPart("key1", "value1")
//                .addFormDataPart("key2", "value2")
//                .build();
//
//        Request request = new Request.Builder()
//                .url("https://api.oioweb.cn/doc/txt/QQFanyi")
//                .post(requestBody)
//                .build();
//
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    final String responseData = response.body().string();
//                    // 处理响应数据
//                }
//            }
//        });
    }

    private void parseAndDisplayData(String jsonData) {
        Gson gson = new Gson();
        // 解析外层JSON对象
        Type resultType = new TypeToken<List<HotSearchItem>>() {}.getType();
        ResultWrapper resultWrapper = gson.fromJson(jsonData, ResultWrapper.class);
        if (resultWrapper != null && resultWrapper.code == 200 && resultWrapper.result != null) {
            List<HotSearchItem> hotSearchItems = gson.fromJson(gson.toJson(resultWrapper.result), resultType);
            runOnUiThread(() -> {
                ArrayAdapter<HotSearchItem> adapter = new ArrayAdapter<HotSearchItem>(MainActivity.this, android.R.layout.simple_list_item_1, hotSearchItems) {
                    @NonNull
                    @Override
                    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                        View view = super.getView(position, convertView, parent);
                        HotSearchItem item = getItem(position);
                        TextView titleView = view.findViewById(android.R.id.text1);
                        titleView.setText(item.getTitle());
                        titleView.setOnClickListener(v -> {
                            String url = item.getLink();
                            if (url != null && !url.isEmpty()) {
                                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                                startActivity(intent);
                            }
                        });
                        return view;
                    }
                };
                listView.setAdapter(adapter);
            });
        } else {
            runOnUiThread(() -> Toast.makeText(MainActivity.this, "解析数据失败", Toast.LENGTH_SHORT).show());
        }
    }

    static class ResultWrapper {
        int code;
        List<HotSearchItem> result;
        String msg;
    }
}